#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/11/1 15:55
# @Description: 对每个仓库进行手动刷新修改
# @Author  : Tom_zc
# @FileName: ci_config.py
# @Software: PyCharm
import yaml
import click
import logging
import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, os.path.join(BASE_DIR, "ci-scripts"))

logging.basicConfig(level=logging.INFO,
                    format="%(asctime)s  %(levelname)s:%(message)s")
from auto_config import EnvClass, WorkFlow

_yaml_config_path = "./refresh_config.yaml"


def _load_yaml(file_path):
    with open(file_path, encoding="utf-8") as fp:
        content = yaml.load(fp.read(), Loader=yaml.Loader)
    return content


def _load_from_yaml():
    config = _load_yaml(_yaml_config_path)
    env_class = EnvClass(
        ak=config["ak"],
        sk=config["sk"],
        obs_endpoint=config["obs_endpoint"],
        obs_static_endpoint=config["obs_static_endpoint"],
        obs_bucket_name=config["obs_bucket_name"],
        majun_domain=config["majun_domain"],
        majun_token=config["majun_token"],
        majun_api_token=config["majun_api_token"],
        gitcode_domain=config["gitcode_domain"],
        gitcode_api_domain=config["gitcode_api_domain"],
        gitcode_username=config["gitcode_username"],
        gitcode_rw_token=config["gitcode_rw_token"],
        gitcode_token=config["gitcode_r_token"],
        conan_user=config["conan_r_user"],
        conan_password=config["conan_r_password"],
        project_id=config["project_id"],
        sca_appId=config["sca_appId"],
        sca_secretKey=config["sca_secretKey"],
        sca_domain=config["sca_domain"],
        image_version=config["image_version"]
    )
    if config.get("repo"):
        repos_lists = config["repo"]
    else:
        repos_dir = os.path.join(BASE_DIR, "ci-repos")
        repos_lists = [dir_name for dir_name in os.listdir(repos_dir) if not dir_name.startswith(".")]
    return env_class, repos_lists


def _load_from_env(repo):
    env_class = EnvClass(
        ak=os.getenv("ak"),
        sk=os.getenv("sk"),
        obs_endpoint=os.getenv("obs_endpoint"),
        obs_static_endpoint=os.getenv("obs_static_endpoint"),
        obs_bucket_name=os.getenv("obs_bucket_name"),
        majun_domain=os.getenv("majun_domain"),
        majun_token=os.getenv("majun_token"),
        majun_api_token=os.getenv("majun_api_token"),
        gitcode_domain=os.getenv("gitcode_domain"),
        gitcode_api_domain=os.getenv("gitcode_api_domain"),
        gitcode_username=os.getenv("gitcode_username"),
        gitcode_rw_token=os.getenv("gitcode_rw_token"),
        gitcode_token=os.getenv("gitcode_r_token"),
        conan_user=os.getenv("conan_r_user"),
        conan_password=os.getenv("conan_r_password"),
        project_id=os.getenv("PROJECT_ID"),
        sca_appId=os.getenv("sca_appId"),
        sca_secretKey=os.getenv("sca_secretKey"),
        sca_domain=os.getenv("sca_domain"),
        image_version=os.getenv("image_version"),
    )
    if repo:
        repos_lists = [repo]
    else:
        repos_dir = os.path.join(BASE_DIR, "ci-repos")
        repos_lists = [dir_name for dir_name in os.listdir(repos_dir) if not dir_name.startswith(".")]
    return env_class, repos_lists


# 读取refresh_config.yaml配置文件，如果里面指定仓库，则对对应的仓库进行修改，否则修改所有的仓库
@click.command()
@click.option("--enable_from_yaml", default=True, help='The choice of read config from yaml or env')
@click.option("--repo", default="", help='The repo of ci')
def main(enable_from_yaml, repo):
    logging.info("-" * 24 + "start to read config from CodeArts pipeline" + "-" * 24)
    if enable_from_yaml:
        env_class, repos_lists = _load_from_yaml()
    else:
        env_class, repos_lists = _load_from_env(repo)
    # 1.从ci-repos获取下面的仓库信息
    # set the env class
    failed_repos = list()
    for ci_repo in repos_lists:
        try:
            logging.info("start to handler:{}".format(ci_repo))
            workflow = WorkFlow(env_class, "openUBMC", ci_repo, "", domain=env_class.gitcode_api_domain)
            workflow.update()
        except Exception as e:
            logging.info("auto_config:{}".format(str(e)))
            failed_repos.append(ci_repo)
    if failed_repos:
        logging.info("find failed repo: {}".format(",".join(failed_repos)))
    logging.info("-" * 24 + "end to auto config ci" + "-" * 24)

if __name__ == '__main__':
    main()
